import type { Dayjs } from 'dayjs';

import type { PageParam, PageResult } from '@vben/request';

import { requestClient } from '#/api/request';

export namespace HandCardAssetApi {


  /** 手牌资产信息 */
  export interface HandCardAsset {
    id: number; // 手牌ID
    resourceId: number; // 资源中台资源ID
    cardNumber?: string; // 手牌号码
    physicsCode: string; // 芯片编号（ID卡编号）
    physicsBankCode: string; // 闸机读取的物理编号
    cardTypeId?: number; // 手牌类型ID
    cardTypeName: string; // 手牌类型名称
    status?: string; // 手牌状态
    previousStatus: string; // 上一个状态
    statusChangeTime: Dayjs | string; // 状态变更时间
    statusChangeReason: string; // 状态变更原因
    storeId?: number; // 门店ID
    orgId?: number; // 组织ID
    groupId?: number; // 所属集团ID
    remarks: string; // 备注
    handcardusages?: HandCardUsage[];
    handcardactionlogs?: HandCardActionLog[];
  }

  /** 手牌使用记录信息 */
  export interface HandCardUsage {
    id: number; // 使用记录ID
    cardId: number; // 手牌ID
    groupId?: number; //
    storeId?: number; //
    identityId?: number; // 关联的身份ID (handcard)
    registryId: number; // 消费登记ID
    teamId: number; // 关联团队/拼房ID
    usageStatus?: string; // 状态(active/closed/suspended)
    roomId: number; // 房间/包间ID
    openTime: Dayjs | string; // 开牌时间
    closeTime: Dayjs | string; // 关牌时间
    depositAmount: number; // 押金金额
    refundAmount: number; // 退款金额
    remarks: string; //
  }

  /** 手牌动作记录表（替换/撤销等）信息 */
  export interface HandCardActionLog {
    id: number; // 主键ID
    groupId?: number; // 集团ID
    storeId?: number; // 门店ID
    cardId: number; // 手牌ID
    oldCardId: number; // 原手牌ID（替换时使用）
    newCardId: number; // 新手牌ID（替换时使用）
    usageId: number; // 使用记录ID（撤销时使用）
    registrationId: number; // 登记ID
    actionCode?: string; // 动作类型
    actionReason?: string; // 动作原因（替换/撤销原因）
    actionAmount: number; // 动作涉及金额（撤销时用）
    actionNotes: string; // 动作说明
    operatorId?: number; // 操作员ID
    operatorName?: string; // 操作员姓名
    scope: string; // 权限范围
    scoperef: string; // 权限引用
  }


}

export interface HandCardStatusStat {
  status: string;
  total: number;
}

/** 查询手牌资产分页 */
export function getHandCardAssetPage(params: PageParam) {
  return requestClient.get<PageResult<HandCardAssetApi.HandCardAsset>>(
    '/spa/hand-card-asset/page',
    { params },
  );
}

/** 手牌使用监控分页响应数据 */
export interface HandCardUsageMonitorItem {
  usageId: string;
  cardId: string;
  cardNumber: string;
  cardStatus: string;
  usageStatus: string;
  groupCode: string;
  businessDay: [number, number, number];
  customerName: null | string;
  customerGender: null | string;
  customerPhone: null | string;
  teamId: null | string;
  teamName: null | string;
  storeId: number;
  openTime: number;
  closeTime: null | number;
  stayMinutes: number;
  childCount: number;
  totalCount: number;
  consumptionTotalAmount: number;
  operatorId: number;
  remarks: string;
  consumptionCode: null | string;
  teamCode: null | string;
  registryId: string;
}

/** 手牌使用监控分页查询参数 */
export interface HandCardUsageMonitorParams extends PageParam {
  cardNumber?: string;
  cardStatus?: string;
  cardTypeId?: number; // 手牌类型ID
  usageStatus?: string;
  groupCode?: string;
  customerName?: string;
  customerGender?: string;
  storeId?: number;
  businessDay?: string;
  registerTime?: string; // 开始时间
  registerTimeEnd?: string; // 结束时间
  onlyActive?: boolean;
}

/** 查询手牌使用监控分页 */
export function getHandCardUsageMonitorPage(
  params: HandCardUsageMonitorParams,
) {
  return requestClient.get<PageResult<HandCardUsageMonitorItem>>(
    '/spa/hand-card-asset/usage/monitor-page',
    { params },
  );
}

/** 查询手牌资产详情 */
export function getHandCardAsset(id: number) {
  return requestClient.get<HandCardAssetApi.HandCardAsset>(
    `/spa/hand-card-asset/get?id=${id}`,
  );
}

/** 新增手牌资产 */
export function createHandCardAsset(data: HandCardAssetApi.HandCardAsset) {
  return requestClient.post('/spa/hand-card-asset/create', data);
}

/** 修改手牌资产 */
export function updateHandCardAsset(data: HandCardAssetApi.HandCardAsset) {
  return requestClient.put('/spa/hand-card-asset/update', data);
}

/** 删除手牌资产 */
export function deleteHandCardAsset(id: number) {
  return requestClient.delete(`/spa/hand-card-asset/delete?id=${id}`);
}


/** 导出手牌资产 */
export function exportHandCardAsset(params: any) {
  return requestClient.download('/spa/hand-card-asset/export-excel', {
    params,
  });
}

/** 下载手牌资产导入模板 */
export function downloadHandCardAssetImportTemplate() {
  return requestClient.download('/spa/hand-card-asset/import-template');
}

/** 导入手牌资产 */
export function importHandCardAsset(file: File) {
  return requestClient.upload('/spa/hand-card-asset/import', {
    file,
  });
}




/** 查询手牌资产详情 */
export function getHandCardStatusEnum() {
  return requestClient.get<any>(`/spa/hand-card-asset/getHandCardStatusEnum`);
}

/** 客户类型手牌状态统计 */
export function getHandCardStatusStatistics() {
  return requestClient.get<HandCardStatusStat[]>(
    '/spa/hand-card-asset/statistics/status-by-customer-type',
  );
}

/** 手牌实时统计 Dashboard 响应数据 */
export interface HandCardDashboardData {
  totalHandCardCount: number;
  freeCount: number;
  occupiedCount: number;
  pendingCount: number;
  forbiddenCount: number;
  selfUseCount: number;
  overtimeCount: number;
  overLimitCount: number;
  todayFlow: number;
  yesterdayFlow: number;
}

/** 获取手牌实时统计 Dashboard */
export function getHandCardDashboard() {
  return requestClient.get<HandCardDashboardData>(
    '/spa/hand-card-asset/usage/dashboard',
  );
}

// ==================== 子表（手牌使用记录） ====================

/** 获得手牌使用记录列表 */
export function getHandCardUsageListByCardId(cardId: number) {
  return requestClient.get<HandCardAssetApi.HandCardUsage[]>(
    `/spa/hand-card-asset/hand-card-usage/list-by-card-id?cardId=${cardId}`,
  );
}

/** 获得手牌使用记录分页 */
export function getHandCardUsagePage(params: PageParam) {
  return requestClient.get<PageResult<HandCardAssetApi.HandCardUsage>>(
    `/spa/hand-card-asset/hand-card-usage/page`,
    { params },
  );
}
/** 新增手牌使用记录 */
export function createHandCardUsage(data: HandCardAssetApi.HandCardUsage) {
  return requestClient.post(
    `/spa/hand-card-asset/hand-card-usage/create`,
    data,
  );
}

/** 修改手牌使用记录 */
export function updateHandCardUsage(data: HandCardAssetApi.HandCardUsage) {
  return requestClient.put(`/spa/hand-card-asset/hand-card-usage/update`, data);
}

/** 删除手牌使用记录 */
export function deleteHandCardUsage(id: number) {
  return requestClient.delete(
    `/spa/hand-card-asset/hand-card-usage/delete?id=${id}`,
  );
}


/** 获得手牌使用记录 */
export function getHandCardUsage(id: number) {
  return requestClient.get<HandCardAssetApi.HandCardUsage>(
    `/spa/hand-card-asset/hand-card-usage/get?id=${id}`,
  );
}

// ==================== 子表（手牌动作记录表（替换/撤销等）） ====================
/** 获得手牌动作记录表（替换/撤销等）列表 */
export function getHandCardActionLogListByCardId(cardId: number) {
  return requestClient.get<HandCardAssetApi.HandCardActionLog[]>(
    `/spa/hand-card-asset/hand-card-action-log/list-by-card-id?tenantId=${cardId}`,
  );
}

/** 获得手牌动作记录表（替换/撤销等）分页 */
export function getHandCardActionLogPage(params: PageParam) {
  return requestClient.get<PageResult<HandCardAssetApi.HandCardActionLog>>(
    `/spa/hand-card-asset/hand-card-action-log/page`,
    { params },
  );
}
/** 新增手牌动作记录表（替换/撤销等） */
export function createHandCardActionLog(
  data: HandCardAssetApi.HandCardActionLog,
) {
  return requestClient.post(
    `/spa/hand-card-asset/hand-card-action-log/create`,
    data,
  );
}

/** 修改手牌动作记录表（替换/撤销等） */
export function updateHandCardActionLog(
  data: HandCardAssetApi.HandCardActionLog,
) {
  return requestClient.put(
    `/spa/hand-card-asset/hand-card-action-log/update`,
    data,
  );
}

/** 删除手牌动作记录表（替换/撤销等） */
export function deleteHandCardActionLog(id: number) {
  return requestClient.delete(
    `/spa/hand-card-asset/hand-card-action-log/delete?id=${id}`,
  );
}


/** 获得手牌动作记录表（替换/撤销等） */
export function getHandCardActionLog(id: number) {
  return requestClient.get<HandCardAssetApi.HandCardActionLog>(
    `/spa/hand-card-asset/hand-card-action-log/get?id=${id}`,
  );
}


// ==================== 消费明细（使用记录相关） ====================
export namespace HandCardConsumptionApi {
  /** 消费详情查询请求 */
  export interface ConsumptionDetailsQuery {
    cardId: number;
    cardNumber?: string;
    onlyActive?: boolean;
    registryId?: number;
    billStatus?: string;
    startTime?: string;
    endTime?: string;
  }

  /** 消费详情响应 */
  export interface ConsumptionDetailsResponse {
    usageRecord: any;
    consumptionRegistry: any;
    consumptionBill: any;
    consumptionDetails: any[];
    totalAmount: number | string;
    paidAmount: number | string;
    payableAmount: number | string;
    discountAmount: number | string;
    status: string;
    startTime: string;
    endTime: string;
    durationMinutes: number;
  }

  /** V2 查询请求（更丰富过滤条件+分页） */
  export interface ConsumptionQueryV2 {
    cardId?: number;
    cardNumber?: string;
    onlyActive?: boolean;
    customerId?: number;
    customerName?: string;
    customerPhone?: string;
    teamId?: number;
    roomId?: number;
    roomNumber?: string;
    usageStatus?: string;
    billNumber?: string;
    detailStatus?: string;
    goodsId?: number;
    goodsName?: string;
    technicianId?: number;
    technicianName?: string;
    minAmount?: number | string;
    maxAmount?: number | string;
    isPaid?: boolean;
    paymentMethod?: string;
    usePoints?: boolean;
    useCoupon?: boolean;
    couponId?: number;
    storeId?: number;
    groupId?: number;
    remark?: string;
    createTimeStart?: string;
    createTimeEnd?: string;
    updateTimeStart?: string;
    updateTimeEnd?: string;
    orderBy?: string;
    orderDirection?: 'asc' | 'desc';
    pageNo?: number;
    pageSize?: number;
  }

  /** V2 查询响应（整合视图对象） */
  export interface ConsumptionQueryV2Response {
    cardId: number;
    cardNumber: string;
    cardStatus: string;
    consumptionRegistry?: any;
    registryId?: number;
    activeUsageRecords?: any[];
    currentUsageRecord?: any;
    consumptionBills?: any[];
    currentBill?: any;
    allConsumptionDetails?: any[];
    billConsumptionDetails?: Array<{
      bill: any;
      billPaidAmount: number;
      billPendingAmount: number;
      billTotalAmount: number;
      details: any[];
    }>;
    totalAmount?: number;
    paidAmount?: number;
    pendingAmount?: number;
    totalDiscountAmount?: number;
    totalPointsUsed?: number;
    totalPointsEarned?: number;
    firstUsageTime?: string;
    lastUsageTime?: string;
    totalDurationMinutes?: number;
    hasUnpaidBills?: boolean;
    hasActiveServices?: boolean;
    overallStatus?: string;
  }
}

/** 获取手牌消费详情列表（可仅查询使用中的记录） */
export function getHandCardConsumptionDetails(
  data: HandCardConsumptionApi.ConsumptionDetailsQuery,
) {
  return requestClient.post<
    HandCardConsumptionApi.ConsumptionDetailsResponse[]
  >('/spa/hand-card-asset/consumption/active-detail-v2', data);
}

/** V2：根据手牌查询消费账单及明细（整合视图） */
export function queryHandCardConsumptionV2(
  data: HandCardConsumptionApi.ConsumptionQueryV2,
) {
  return requestClient.post<{
    code: number;
    data: HandCardConsumptionApi.ConsumptionQueryV2Response;
  }>('/spa/hand-card-asset/consumption/query-page-v2', data);
}

// ==================== 消费-商品购买 ====================
export namespace GoodsPurchaseApi {
  export interface GoodsItem {
    goodsId: number;
    goodsName: string;
    goodsType: string;
    quantity: number;
    unitPrice: number;
    discountAmount?: number;
    subtotalAmount?: number;
    staffId?: number;
    staffCommission?: number;
    specification?: string;
    unit?: string;
    description?: string;
    remark?: string;
  }

  export interface GoodsPurchasePayload {
    billId?: number;
    cardId: number;
    operatorId?: number;
    remark?: string;
    goodsItems: GoodsItem[];
  }

  export interface CalculateResponse {
    totalAmount: number;
    payableAmount?: number;
    discountAmount?: number;
    items?: Array<{ goodsId: number; subtotalAmount: number }>;
  }

  export interface SubmitResponse {
    successCount: number;
    totalAmount: number;
  }
}

/** 计算商品购买金额 */
export function calculateGoodsPurchase(
  data: GoodsPurchaseApi.GoodsPurchasePayload,
) {
  return requestClient.post<GoodsPurchaseApi.CalculateResponse>(
    '/spa/consumption-detail/goods-purchase/calculate',
    data,
    {
      headers: {
        'X-Group-Id': 1,
        'X-Store-Id': 10,
        'X-Site-Id': 100,
        'X-Org-Id': 1000,
      },
    },
  );
}

/** 提交商品购买 */
export function submitGoodsPurchase(
  data: GoodsPurchaseApi.GoodsPurchasePayload,
) {
  return requestClient.post<GoodsPurchaseApi.SubmitResponse>(
    '/spa/consumption-detail/goods-purchase',
    data,
    {
      headers: {
        'X-Group-Id': 1,
        'X-Store-Id': 10,
        'X-Site-Id': 100,
        'X-Org-Id': 1000,
      },
    },
  );
}
// ==================== 手牌操作 ====================
// 开牌
export function openHandCard(data: any) {
  return requestClient.post('/spa/hand-card/mgmt/open', data);
}
